package com.sun.springsecruity.service;

import com.sun.springsecruity.bean.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    /**
     * 根据表单提交的用户名查询User对象，并装配角色权限等信息
     *
     * @param username 表单提交的用户名
     * @return userDetails
     * @throws UsernameNotFoundException  查询错误
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 根据用户名在数据库中查询
        String sql ="select id,loginacct,userpswd,username ,email from t_admin where loginacct= ?";
        List<Admin> list=jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Admin.class), username);

        if (list.size()==0) {
            throw new UsernameNotFoundException("无法查找到用户" + username);
        }
        Admin admin = list.get(0);
        // 2. 给admin设置角色信息
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 添加角色
        authorities.add(new SimpleGrantedAuthority("Role_ADMIN"));
        // 添加权限
        authorities.add(new SimpleGrantedAuthority("UPDATE"));

        // 把admin对象和authorities封装到userDetials 中
        return new User(username, admin.getUserpswd(), authorities);
    }
}
